package com.zuorenke.help;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * @author Z.R.K
 * @description
 * @create 2019-04-10 14:37:30
 **/
public class StringUtils {
	private StringUtils(){}
	private static ObjectMapper mapper = new ObjectMapper();
	public static String[] splitByChar(String splitStr, char splitKey, int size) {
		String[] result = new String[size];
		int index = 0;
		int length = splitStr.length();
		int begin = 0;
		for (int j = 0; j < length; j++) {
			char curChar = splitStr.charAt(j);
			if (index + 1 >= size) {
				break;
			}
			if(curChar == splitKey){
				if(begin == j){
					begin ++;
				}else{
					result[index] = splitStr.substring(begin, j);
					begin = j+1;
					index ++;
				}
			}
		}
		if(index < size) result[index] =  splitStr.substring(begin);
		return result;
	}
	
	public static boolean isEmpty (String string){
		return string == null || string.length() == 0;
	}
	public static boolean isNotEmpty (String string){
		return string != null && string.length() > 0;
	}
	
	public static String capitalize(String str) {
		int strLen;
		if (str == null || (strLen = str.length()) == 0) {
			return str;
		}
		return new StringBuilder(strLen).append(Character.toTitleCase(str.charAt(0))).append(str.substring(1)).toString();
	}

	public static <T> String objectToJson(T t){
		try {
			return mapper.writeValueAsString(t);
		} catch (JsonProcessingException e) {
			return "{}";
		}
	}

	public static <T> T jsonToObject(String json, Class<T> clazz){
		try {
			return mapper.readValue(json, clazz);
		} catch (IOException e) {
			return null;
		}
	}
}
